package com.yupi.springbootinit.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class ToolUtils {
    static String apiURL = "https://api.map.baidu.com/reverse_geocoding/v3/";
    static String apiKey = "64uvOJXlda4Thsunr2rNhzAM4M1IHGRA";
    static String outputType = "json";
    //地址格式为gps
    static String coordType = "wgs84ll";

    public static String getLocationByGps(String gpsLocation) throws IOException {
        //默认传参的地址是(经度lng,纬度lat),但api接口需要(纬度,经度)的格式
        String[] split = gpsLocation.split(",");
        String formatGpsLocation = split[1] + "," + split[0];
        URL url = new URL(apiURL + "?ak=" + apiKey + "&output=" + outputType + "&coordtype=" + coordType + "&location=" + formatGpsLocation);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        ObjectMapper objectMapper = new ObjectMapper();
        // 将JSON字符串转换为Map
        Map<String, Object> dataMap = objectMapper.readValue(response.toString(), new TypeReference<Map<String, Object>>() {});
        HashMap<String,Object> result = (HashMap<String,Object>) dataMap.get("result");
        String formatted_address = result.get("formatted_address").toString();
        return formatted_address;
    }

}
